package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.BaseContext;
import com.itheima.entity.OrderDetail;
import com.itheima.entity.ShoppingCart;
import com.itheima.mapper.ShoppingCartMapper;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Autowired
    private ShoppingCartService shoppingCartService;


    @Override
    public void clean() {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        shoppingCartService.remove(queryWrapper);
    }

    @Override
    //抽到service的代码
    public void addCart(List<OrderDetail> orderDetails,Long userid){

        List<ShoppingCart> shoppingCarts = orderDetails.stream().map(item ->{
            //把数据赋给购物车
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userid);
            shoppingCart.setImage(item.getImage());
            shoppingCart.setNumber(item.getNumber());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if(dishId != null){
                //添加菜品
                shoppingCart.setDishId(dishId);
            }else {
                //添加套餐
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setName(item.getName());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(shoppingCarts);
    }


}
